//
//  WalletDetailsController.m
//  SafPay
//
//  Created by 贺庆博 on 2018/6/19.
//  Copyright © 2018年 ebo. All rights reserved.
//

#import "WalletDetailsController.h"
#import "UIButton+Layout.h"
#import "WalletDetailsCell.h"
#import "TransferInController.h"
#import "TransferOutController.h"
#import "TDTitleBtn.h"
#import "ChoseCoinController.h"
#import "TDNoDataView.h"
@interface WalletDetailsController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSString *money;
    UILabel *titleLab;
}
@property (strong,nonatomic) UILabel *totalLab;
@property (strong,nonatomic) UILabel *cnyLab;
@property (strong,nonatomic) UITableView *tableView;
@property (strong,nonatomic) TDNoDataView *dataView;
@property (strong,nonatomic) NSMutableArray *arrDS;
@property (weak,nonatomic) TDTitleBtn *rightbtn;
@property (nonatomic , strong)dispatch_source_t timer;

@end

@implementation WalletDetailsController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = self.coinname;
    [self initUI];
    [self initNav];
    [self startTimer];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.timer) {
        dispatch_cancel(self.timer);
        
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.timer) {
        [self startTimer];
        
    }
  
}
//定时器轮询
- (void)startTimer
{
    //获得队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    //创建一个定时器
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //设置开始时间
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC));
    //设置时间间隔
    uint64_t interval = (uint64_t)([GTimeLength floatValue] * NSEC_PER_SEC);
    //设置定时器
    dispatch_source_set_timer(self.timer, start, interval, 0);
    //设置回调
    dispatch_source_set_event_handler(self.timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            UIApplicationState state = [UIApplication sharedApplication].applicationState;
            if (state == UIApplicationStateActive){
                [self loadData];
            };
        });
    });
    //启动定时器
    dispatch_resume(self.timer);
}

- (void)loadData{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.coinname forKey:@"coinname"];
    [dic setValue:[AccountTools shared].currentAccount.token forKey:@"token"];
    [dic setValue:[AccountTools shared].currentAccount.userId forKey:@"uid"];
    [dic setValue:self.wid forKey:@"wid"];
//    __weak typeof (NSString *)weakMoney = money;
    [[TRRequest request] Post:kSetURL(kCoinDetails) parameters:dic success:^(TRRequest *request, NSDictionary *responseDict) {
        
        if ([[responseDict valueForKey:@"error"] integerValue] == 0) {
            [self.arrDS removeAllObjects];
            NSDictionary *dict = [responseDict valueForKey:@"data"];
            self->money = [dict valueForKey:@"coin_num"];
            self.totalLab.text = [NSString stringWithFormat:@"%@ %@",[dict valueForKey:@"coin_num"],self.coinname];
            self.cnyLab.text = [NSString stringWithFormat:@"￥%@",[dict valueForKey:@"cny_price"]];
            [[dict valueForKey:@"transferrecord"] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                WalletCoinModel *model = [WalletCoinModel new];
                [model yy_modelSetWithDictionary:obj];
                [self.arrDS addObject:model];
            }];
            self.arrDS.count==0?[self.tableView addSubview:self.dataView]:[self.dataView removeFromSuperview];
            [self.tableView reloadData];

        }else
        {
            [MBProgressHUD showErrorWithText:[responseDict valueForKey:@"error_msg"]];
        }
    } failure:^(TRRequest *request, NSError *error) {
        
         self.arrDS.count==0?[self.tableView addSubview:self.dataView]:[self.dataView removeFromSuperview];
        
    }];
}
- (void)initNav
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kNavHeight)];
    [self.view addSubview:view];
    
    TDTitleBtn * rightbtn = [[TDTitleBtn alloc]initWithFrame:CGRectMake(kScreenWidth - 80 - 15, kNavHeight - 35, 80, 23)];
    rightbtn.layer.cornerRadius = 11;
    rightbtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    rightbtn.titleLabel.textAlignment = 1;
    rightbtn.titleLabel.font = kFONT(12);
    [rightbtn setTitle:self.coinname?:@"--" forState:UIControlStateNormal];
    [rightbtn setImage:kImageName(@"arrow_down") forState:UIControlStateNormal];
    [rightbtn setImage:kImageName(@"arrow_up") forState:UIControlStateSelected];
    rightbtn.layer.borderColor = [kTradeWhiteColor CGColor];
    rightbtn.layer.borderWidth = 0.5f;
    [rightbtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:rightbtn];
    self.rightbtn = rightbtn;
    
    titleLab = [UILabel labelWithFrame:CGRectMake(0, 0, 200, 20) font:kFONT(17) color:[UIColor whiteColor] text:self.coinname?:@"--"];
    titleLab.yzCenterX = kScreenWidth/2;
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.yzCenterY = rightbtn.yzCenterY;
    [view addSubview:titleLab];
    
    UIButton *leftBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setFrame:CGRectMake(15, kNavHeight - 37, 30, 30)];
    [leftBtn setImage:[UIImage imageNamed:@"icon_left_arrow"] forState:UIControlStateNormal];
    [view addSubview:leftBtn];
    [[leftBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
}

- (void)btnClick:(TDTitleBtn*)btn
{
    ChoseCoinController *vc = [ChoseCoinController new];
    
    vc.coinClickBlock = ^(CoinListModel *model) {
        self.coinname = model.name;
        self->titleLab.text = self.coinname;
        [self.rightbtn setTitle:model.name forState:UIControlStateNormal];
        [self loadData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)initUI
{
    UIImageView *img = [UIImageView new];
    img.image = kImageName(@"fang_bg");
    [self.view addSubview:img];
    [img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.equalTo(self.view);
    }];
    
    self.totalLab = [UILabel labelWithFont:kFONT(31) color:[UIColor whiteColor] text:@"--"];
    self.totalLab.textAlignment = NSTextAlignmentCenter;
    self.cnyLab = [UILabel labelWithFont:kFONT(19) color:[UIColor whiteColor] text:@"￥--"];
    self.cnyLab.textAlignment = NSTextAlignmentCenter;
    UIButton *turnInBtn = [UIButton new];
    [turnInBtn setImage:kImageName(@"transfer_in") forState:UIControlStateNormal];
    [turnInBtn setTitle:@"转入" forState:UIControlStateNormal];
    [turnInBtn setTitleColor:rgb(38,107,170) forState:UIControlStateNormal];
    turnInBtn.layer.cornerRadius = 19;
    turnInBtn.backgroundColor = [UIColor whiteColor];
    turnInBtn.titleLabel.font = kFONT(16);
    [[turnInBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        TransferInController *vc = [TransferInController new];
        vc.type = self.coinname;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    UIButton *turnOutBtn = [UIButton new];
    [turnOutBtn setImage:kImageName(@"transfer_out") forState:UIControlStateNormal];
    turnOutBtn.layer.cornerRadius = 19;
    [turnOutBtn setTitle:@"转出" forState:UIControlStateNormal];
    turnOutBtn.backgroundColor = [UIColor whiteColor];
    [turnOutBtn setTitleColor:rgb(38,107,170) forState:UIControlStateNormal];
    turnOutBtn.titleLabel.font = kFONT(16);
    [[turnOutBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        TransferOutController *vc = [TransferOutController new];
        vc.type = self.coinname;
        vc.money = self->money;
        vc.wid=self.wid;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    [self.view addSubview:self.totalLab];
    [self.view addSubview:self.cnyLab];
    [self.view addSubview:turnInBtn];
    [self.view addSubview:turnOutBtn];
    [self.view addSubview:self.tableView];

    [self.totalLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(60+kNavHeight);
        make.left.right.equalTo(self.view);
    }];
    [self.cnyLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.totalLab.mas_bottom).mas_offset(27);
        make.left.right.equalTo(self.view);
    }];
    [turnInBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.cnyLab.mas_bottom).mas_offset(50);
        make.centerX.equalTo(self.view).offset(-72);
        make.width.mas_equalTo(120);
        make.height.mas_equalTo(38);
    }];
    [turnOutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.width.height.mas_equalTo(turnInBtn);
        make.centerX.equalTo(self.view).offset(72);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(turnOutBtn.mas_bottom).mas_offset(37);
        make.left.equalTo(self.view).offset(6);
        make.right.equalTo(self.view).offset(-6);
        make.bottom.equalTo(self.view);
    }];
    
    [turnInBtn sc_setLayoutStyle:SCButtonLayoutStyleImageLeft spacing:10];
    [turnOutBtn sc_setLayoutStyle:SCButtonLayoutStyleImageLeft spacing:10];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 49)];
    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(16, 13, 23, 23)];
    img.image =kImageName(@"transfer_record");
    UILabel *lab = [UILabel labelWithFrame:CGRectMake(49, 13, 200, 23) font:kFONT(15) color:rgb(75,74,74) text:@"转账记录"];
    [header addSubview:img];
    [header addSubview:lab];
    return header;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 49;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrDS.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WalletDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WalletDetailsCell"];
    cell.model = self.arrDS[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (NSMutableArray *)arrDS
{
    if (!_arrDS) {
        _arrDS = [NSMutableArray array];
    }
    return _arrDS;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]init];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.rowHeight = 63;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:@"WalletDetailsCell" bundle:nil] forCellReuseIdentifier:@"WalletDetailsCell"];
    }
    return _tableView;
}
- (TDNoDataView *)dataView{
    if (!_dataView) {
        _dataView = [[TDNoDataView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) img:nil title:@"暂无转账记录"];
        
        
    }
    return _dataView;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
